import 'dart:developer';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:get/get.dart';
import 'package:guochaoapp/r.dart';
import 'package:guochaoapp/controller/home/home_controller.dart';

class GCHomePage extends StatefulWidget {
  @override
  _GCHomePageState createState() => _GCHomePageState();
}

class _GCHomePageState extends State<GCHomePage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  final c = Get.put(GCHomeController());

  @override
  Widget build(BuildContext context) {
    return _initSubviews();
  }

  @override
  void initState() {
    super.initState();

    c.requestVersion();
    c.requestTelephone();
    c.requestBannerList();
    c.requestProductBrand();
  }

  _initSubviews() {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      body: Container(
        child: ListView(
          padding: EdgeInsets.only(top: 0),
          children: [
            Stack(
              children: [
                Image.asset(R.assetsIconHomeMask, fit: BoxFit.cover, width: double.infinity),
                Column(
                  children: [
                    _topToolsView(),
                    SizedBox(height: 10),
                    _swiperViews(),
                    SizedBox(height: 10),
                    _shoppingView(),
                    SizedBox(height: 10),
                    _priceUpDownView(),
                    SizedBox(height: 10),
                    _priceChartView(),
                    SizedBox(height: 10)
                  ],
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

  //顶部 定位 和 客服按钮
  _topToolsView() {
    return Container(
      height: ScreenUtil().setHeight(ScreenUtil().statusBarHeight + 20),
      child: Column(
        children: [
          Container(height: ScreenUtil().statusBarHeight),
          Expanded(
            child: GestureDetector(
              onTap: c.localtonTap,
              child: Row(
                children: [
                  SizedBox(width: ScreenUtil().setWidth(29)),
                  Obx(() => Text(
                        "${c.cityName}",
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(18),
                            color: Colors.white,
                            fontWeight: FontWeight.w400),
                      )),
                  Icon(Icons.keyboard_arrow_down, color: Colors.white),
                  Expanded(child: SizedBox()),
                  GestureDetector(
                    onTap: c.kfTap,
                    child: Image.asset(R.assetsIconHomeKf, width: 22, height: 22),
                  ),
                  SizedBox(width: ScreenUtil().setWidth(24))
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  //轮播图
  _swiperViews() {
    return Container(
        height: ScreenUtil().setHeight(200),
        margin: EdgeInsets.only(left: ScreenUtil().setSp(8), right: ScreenUtil().setSp(8)),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.0),
        ),
        child: Obx(() => Container(
              child: Swiper(
              key: UniqueKey(),
              itemBuilder: (context, index) {
                return CachedNetworkImage(imageUrl: c.bannerList[index].cover, fit: BoxFit.fill);
              },
              itemCount: c.bannerList.length,
              pagination: new SwiperPagination(),
              scrollDirection: Axis.horizontal,
              autoplay: true,
              onTap: (index) => print('点击了第$index个'),
            )))
        );
  }

  // 商城 和 定制支架
  _shoppingView() {
    return Container(
      height: 110,
      child: Column(
        children: [
          Row(
            children: [
              SizedBox(width: 8),
              Text("果巢商城",
                  style: TextStyle(
                      color: Color(0xFF333333),
                      fontSize: ScreenUtil().setSp(16),
                      fontWeight: FontWeight.bold))
            ],
          ),
          SizedBox(height: 6),
          Expanded(
              child: Row(
            children: [
              _shoppingItem(R.assetsIconHomeGg, "钢管", () => c.toMalls(0)),
              _shoppingItem(R.assetsIconHomeMggj, "玛钢管件", () => c.toMalls(1)),
              _shoppingItem(R.assetsIconHomeGcgj, "沟槽管件", () => c.toMalls(2)),
              _shoppingItem(R.assetsIconHomeXc, "型材", () => c.toMalls(3)),
              _shoppingItem(R.assetsIconHomeFc, "辅材", () => c.toMalls(4)),
            ],
          ))
        ],
      ),
    );
  }

  _shoppingItem(String imageNamed, String title, Function itemTap) {
    return GestureDetector(
      onTap: itemTap,
      child: Container(
        width: ScreenUtil().screenWidth / 5.0,
        child: Column(
          children: [
            Image.asset(imageNamed, width: 48, height: 48),
            SizedBox(height: 5),
            Text(title,
                style: TextStyle(color: Color(0xFF333333), fontSize: 12)),
          ],
        ),
      ),
    );
  }

  /*
  _oldContainer() {
    return Container(
      height: 94,
      child: Padding(
        padding: const EdgeInsets.only(left: 10.0, right: 10.0),
        child: Row(children: [
          _shoppingAndBarcketItem("果巢商城", "类别1|类别2|类别3", "立即选购>",
              R.assetsIconHomeShopping, c.toShopping),
          SizedBox(width: 3),
          _shoppingAndBarcketItem("定制支架", "类别1|类别2|类别3", "开始定制>",
              R.assetsIconHomeBarcket, c.toBarcket),
        ]),
      ),
    );
  }


  _shoppingAndBarcketItem(String title, String subTitle, String actionName,
      String iconName, Function iconTap) {
    return Expanded(
      child: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5.0),
                color: Colors.white,
                border: Border.all(
                  color: Color(0xFFE5F3F4),
                  width: 1.0,
                  style: BorderStyle.solid,
                )),
            padding: const EdgeInsets.all(5),
            child: Row(
              children: [
                Column(children: [
                  Text(title,
                      style: TextStyle(
                          color: Color(0xFF333333),
                          fontSize: ScreenUtil().setSp(16),
                          fontWeight: FontWeight.bold)),
                  SizedBox(height: 6),
                  Text(subTitle,
                      style: TextStyle(
                        color: Color(0xFFB5B5B5),
                        fontSize: ScreenUtil().setSp(10),
                      )),
                  SizedBox(height: 10),
                  Container(
                    height: ScreenUtil().setHeight(25),
                    child: RaisedButton(
                        color: Theme.of(context).primaryColor,
                        onPressed: iconTap,
                        child: Text(actionName,
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil().setSp(12)))),
                  )
                ]),
                Expanded(
                    child: Column(children: [
                  Expanded(child: SizedBox()),
                  title == "果巢商城"
                      ? Image.asset(
                          iconName,
                          height: 46,
                          width: 47,
                        )
                      : Image.asset(
                          iconName,
                          height: 59,
                          width: 72,
                        )
                ]))
              ],
            ),
          ),
          Row(
            children: [
              Expanded(child: SizedBox()),
              Image.asset(R.assetsIconHomeHot, height: 15, width: 36),
            ],
          )
        ],
      ),
    );
  }

   */

  _priceUpDownView() {
    return Container(
      padding: const EdgeInsets.only(left: 8, right: 8),
//      height: 20,
      child: Row(children: [
        Text("最近价格涨跌",
            style: TextStyle(
                color: Color(0xFF333333),
                fontSize: ScreenUtil().setSp(16),
                fontWeight: FontWeight.bold)),
        SizedBox(width: 10),
        Expanded(
          child: Container(
              height: 22,
              child: Obx(
                () => ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (context, index) {
                    return _priceSourceItem(index, () {
                      c.brandSelectIndex = index;
                      this.setState(() {});
                    });
                  },
                  itemCount: c.productbrandList.length,
                ),
              )),
        )
      ]),
    );
  }

  _priceSourceItem(int index, Function tapcallback) {
    return GestureDetector(
      onTap: () {
        tapcallback();
      },
      child: Container(
          decoration: BoxDecoration(
              color: c.brandSelectIndex == index
                  ? Color(0xFF40A8B3)
                  : Colors.transparent,
              borderRadius: BorderRadius.all(Radius.circular(2))),
          width: 50,
          child: Center(
              child: Text(c.productbrandList[index].brandName,
                  style: TextStyle(
                      color: c.brandSelectIndex == index
                          ? Colors.white
                          : Color(0xFF333333),
                      fontSize: 14)))),
    );
  }

  //图表
  _priceChartView() {
    return Container(
        padding: EdgeInsets.only(left: 8, right: 8),
        height: 267,
        child: Card(
          elevation: 0,
          child: Container(
            decoration: BoxDecoration(
              border: new Border.all(color: Color(0xFFE5F3F4), width: 1),
              color: Colors.white, // 底色
              borderRadius: new BorderRadius.circular(8),
            ),
            child: Obx(() => Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  mainAxisAlignment: MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    SizedBox(height: 10),
                    GestureDetector(
                      onTap: c.toBenchMarkDetail,
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          const SizedBox(
                            width: 27,
                          ),
                          const Text(
                            '镀锌钢管',
                            style: TextStyle(
                                color: Color(0xFF5B5B5B), fontSize: 14),
                          ),
                          Expanded(child: SizedBox()),
                          const Text(
                            '上涨指数',
                            style: TextStyle(
                                color: Color(0xFF5B5B5B), fontSize: 8),
                          ),
                          const SizedBox(width: 66),
                        ],
                      ),
                    ),
                    GestureDetector(
                      onTap: c.toBenchMarkDetail,
                      child: Container(
                        height: 50,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            const SizedBox(
                              width: 27,
                            ),
                            Text(
                              c.benchmarkList.length > 0
                                  ? "¥${c.benchmarkList[0].currentBenchmark.toInt().toString()}"
                                  : "0",
                              style: TextStyle(
                                  color: Color(0xFFF75554),
                                  fontSize: 36,
                                  fontWeight: FontWeight.bold),
                            ),
                            Expanded(child: SizedBox()),
                            Row(
                              children: [
                                Text(
                                  c.benchmarkList.length > 0
                                      ? "${c.benchmarkList[0].changeTotal.toInt().toString()}"
                                      : "0",
                                  style: TextStyle(
                                      color: Color(0xFFF75554),
                                      fontSize: 24,
                                      fontWeight: FontWeight.bold),
                                ),
                                Column(
                                  children: [
                                    Icon(Icons.arrow_upward,
                                        color: Color(0xFFF75554)),
                                    SizedBox(height: 20)
                                  ],
                                )
                              ],
                            ),
                            const SizedBox(width: 39),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 30.0),
                        child: BarChart(
                          BarChartData(
                            maxY:  c.maxBenchmark + (100 - c.maxBenchmark % 100),
                            minY: c.minBenchmark - c.minBenchmark % 100 - 200,
                            titlesData: FlTitlesData(
                              show: true,
                              bottomTitles: SideTitles(
                                showTitles: true,
                                getTextStyles: (value) => const TextStyle(
                                    color: Color(0x57333333),
                                    fontWeight: FontWeight.normal,
                                    fontSize: 10),
                                margin: 15,
                                getTitles: (double value) {
                                  int index = value.toInt();
                                  var listString = c
                                      .benchmarkList[index].createAt
                                      .split("-");
                                  return "${listString[1]}.${listString[2]} \n${listString[0]}";
                                },
                              ),
                              leftTitles: SideTitles(
                                interval: (c.maxBenchmark - c.minBenchmark)/2 ,
                                showTitles: true,
                                getTextStyles: (value) => const TextStyle(
                                    color: Color(0x57333333),
                                    fontWeight: FontWeight.normal,
                                    fontSize: 10),
                                margin: 30,
                                reservedSize: 20,
                           getTitles: (value) {
                                  log(value.toString());
                             return value.toInt().toString();
                           },
                              ),
                            ),
                            borderData: FlBorderData(
                              show: false,
                            ),
                            barGroups: c.barchatGroupList,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: 14),
                  ],
                )),
          ),
        ));
  }
}
